package com.dxy.hms.socketio;

import com.corundumstudio.socketio.AuthorizationResult;
import com.corundumstudio.socketio.SocketIOServer;
import com.dxy.hms.utils.JwtUtil;
import com.dxy.hms.utils.LoginUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Configuration
@EnableConfigurationProperties(SocketIoProperties.class)
public class SocketIoConfig {

    @Autowired
    private SocketIoProperties socketIoProperties;

    @Bean
    public SocketIOServer socketIOServer() {
        com.corundumstudio.socketio.Configuration configuration = new com.corundumstudio.socketio.Configuration();
        configuration.setHostname(socketIoProperties.getHost());
        configuration.setPort(socketIoProperties.getPort());
        com.corundumstudio.socketio.SocketConfig socketConfig = new com.corundumstudio.socketio.SocketConfig();
        socketConfig.setReuseAddress(true);
        configuration.setSocketConfig(socketConfig);
        configuration.setOrigin(null);
        configuration.setBossThreads(socketIoProperties.getBossCount());
        configuration.setWorkerThreads(socketIoProperties.getBossCount());
        configuration.setAllowCustomRequests(socketIoProperties.isAllowCustomRequests());
        configuration.setUpgradeTimeout(socketIoProperties.getUpgradeTimeout());
        configuration.setPingTimeout(socketIoProperties.getPingTimeout());
        configuration.setPingInterval(socketIoProperties.getPingInterval());
        configuration.setMaxHttpContentLength(socketIoProperties.getMaxHttpContentLength());
        configuration.setMaxFramePayloadLength(socketIoProperties.getMaxFramePayloadLength());

        // 设置连接鉴权
        configuration.setAuthorizationListener(data -> {
            //获取socket链接发来的token参数（http://localhost:20001?token=xxx）
            String token=data.getSingleUrlParam("token");
            //这个isPass是我的验签token方法,如果验签通过就是true,否则false,false的话就不允许建立socket链接
            if (LoginUtil.checkLogin(token) && JwtUtil.verifyToken(token)){
                return AuthorizationResult.SUCCESSFUL_AUTHORIZATION;
            }else {
                return AuthorizationResult.FAILED_AUTHORIZATION;
            }
        });

        log.info("socketio服务端初始化...");
        return new SocketIOServer(configuration);
    }
}
